/*
 * @lc app=leetcode.cn id=15 lang=typescript
 *
 * [15] 三数之和
 */

// @lc code=start
function threeSum(nums: number[]): number[][] {
  if (nums.length < 3) { return [] }
  const list:number[][] = []
  nums.sort((a, b) => a - b)
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] > 0) break;
    if (i > 0 && nums[i] === nums[i - 1]) continue;
    let left = i + 1;
    let right = nums.length - 1;
    while (left < right) {
      // since left < right, and left > i, no need to compare i === left and i === right.
      if (nums[left] + nums[right] + nums[i] === 0) {
        list.push([nums[left], nums[right], nums[i]]);
        // skip duplicated result without set
        while (nums[left] === nums[left + 1]) {
          left++;
        }
        left++;
        // skip duplicated result without set
        while (nums[right] === nums[right - 1]) {
          right--;
        }
        right--;
        continue;
      } else if (nums[left] + nums[right] + nums[i] > 0) {
        right--;
      } else {
        left++;
      }
    }
  }
  return list.map(n=>{
    return n.sort((a,b)=>a-b)
  })
};
/**
 * 判断是否存在
 */
function listHasVal(reList: number[][], list: number[]): boolean {
  // if(!list||!n){return false}
  for (let i = 0; i < reList.length; i++) {
    if (list.includes(reList[i][0]) && list.includes(reList[i][1]) && list.includes(reList[i][2])) {
      return true
    }
  }
  return false
}
// @lc code=end
